package pl.edu.agh.nn.data.producer;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;

import pl.edu.agh.nn.conf.InvalidNetworkConfigurationException;
import pl.edu.agh.nn.data.NetData;

public class FileOutputProducer implements OutputDataProducer {

	private List<NetData> outputData;
	private String file;

	public FileOutputProducer() {

	}

	public FileOutputProducer(String file) {
		this.file = file;
		this.outputData = new ArrayList<NetData>();
	}

	@Override
	public void produce(double[] result) {
		outputData.add(new NetData(result));
	}

	@Override
	public void configure() throws InvalidNetworkConfigurationException {
		this.outputData = new ArrayList<NetData>();
	}

	@Override
	public void finish() {
		saveDataToFile();
	}

	private void saveDataToFile() {
		try {
			BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
			StringBuilder builder = new StringBuilder();
			for (NetData data : outputData) {
				for (double d : data.getData()) {
					builder.append(d).append(", ");
				}
				builder.append("\n");
			}
			bufferedWriter.write(builder.toString());
			bufferedWriter.close();
		} catch (Exception e) {
			System.err.println("Could not save output data");
			e.printStackTrace();
		}
	}

}
